<?php
/**
 * --------------------------------------------------------------
 * 数据模型控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\DataModel as DataModelModel;
use app\admin\model\AuthRule as AuthRuleModel;
use app\admin\model\Field as FieldModel;
use think\Db;

class DataModel extends AdminBase
{
    /**
     * 数据模型列表
     */
    public function index()
    {
        $map  = $this->getSimpleSearchMap();
        $list = DataModelModel::where($map['where'])
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => '数据模型列表'
        ]);
        return $this->fetch();
    }

    /**
     * 新增
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->post();
			
			if ($data['table'] == '') {
                $data['table'] = config('database.prefix') . 'document_' . $data['en_title'];
            } else {
                $data['table'] = str_replace('#@__', config('database.prefix'), $data['table']);
            }
			
			// 验证
            $result   = $this->validate($data, 'DataModel');
            if (true !== $result) $this->error($result);
			
			// 严格验证附加表是否存在
            if (table_exist($data['table'])) {
                $this->error('附加表已存在');
            }
			
			if ($model = DataModelModel::create($data)) {
				// 创建附加表
                if (false === DataModelModel::createTable($model)) {
                    $this->error('创建附加表失败');
                }
				
                // 创建菜单节点
                $map = [
                    'name' => 'substance',
                ];
                $rule_data = [
                    "name"   => "admin/content/{$data['en_title']}",
                    "title"  => $data['title'] . '管理',
                    "type"   => 2,
                    "pid"    => Db::name('auth_rule')->where($map)->value('id'),
                    "sort"   => "100",
                ];
                AuthRuleModel::create($rule_data);
				cache('lyear_data_model_list', null);

                return $this->success('新增成功', url('index'));
            } else {
                return $this->error('新增失败');
            }
        } else {
            $this->assign([
                'title' => '新增数据模型'
            ]);
            return $this->fetch();
        }
    }
	
	/**
	 * 编辑
	 */
	public function edit()
	{
	    $id = input('id/d');
        if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
        if ($this->request->isPost()) {
            $data   = $this->request->post();
			
			// 验证
			$result   = $this->validate($data, 'DataModel.edit');
            if (true !== $result) $this->error($result);

            if (DataModelModel::update($data)) {
                $en_title = DataModelModel::where('id', $id)->value('en_title');
                Db::name('auth_rule')->where(['name' => "admin/content/{$en_title}"])->update(['title' => $data['title'] . '管理']);
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = DataModelModel::get($id);

            $this->assign([
                'info'  => $info,
                'title' => '编辑数据模型'
            ]);
            return $this->fetch();
        }
	}
	
	/**
	 * 删除
	 * @param integer $ids id值
	 */
	public function delete($ids = null)
	{
	    if ($ids === null) $this->error('参数错误');

        $model = DataModelModel::where('id', $ids)->find();
        if ($model['type'] == 0) {
            $this->error('禁止删除系统模型');
        }
		
		// 删除表和字段信息
        if (DataModelModel::deleteTable($ids)) {
		    // 删除主表中的文档
            if (false === Db::name('document')->where('model_id', $ids)->delete()) {
                $this->error('删除主表文档失败');
            }
            // 删除菜单节点
            $map = [
                'name' => "admin/content/{$model['en_title']}"
            ];
            if (false === Db::name('auth_rule')->where($map)->delete()) {
                $this->error('删除权限节点失败');
            }
            // 删除字段数据
            if (false !== Db::name('field')->where('model_id', $ids)->delete()) {
                cache('lyear_data_model_list', null);
                $flag = DataModelModel::where('id', $ids)->delete();
                return $flag !== false ? $this->success('删除成功') : $this->error('删除失败');
            } else {
                return $this->error('删除内容模型字段失败');
            }
		} else {
		    return $this->error('删除内容模型表失败');
		}
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        in_array('1', $ids) && $this->error('不允许禁用系统模型');
        
        $map  = ['id' => $ids];
        $info = DataModelModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }

    /**
     * 数据模型 - 字段列表
     * @param integer $model_id 模型ID
     */
    public function fieldList()
    {
        $model_id = input('model_id/d');
    	if ($model_id <= 0 || !is_numeric($model_id)) $this->error('参数错误');
        
        $modelTitle = DataModelModel::where('id', $model_id)->value('title');

        $andWhere = ['model_id' => $model_id];
        $map      = $this->getSimpleSearchMap();

        $map['conditions'] = array_merge($map['conditions'], $andWhere);

        $list = FieldModel::where($map['where'])
                ->where($andWhere)
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'model_id'     => $model_id,
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => $modelTitle . '模型 - 字段列表'
        ]);
        return $this->fetch();
    }

    /**
     * 数据模型 - 新增字段
     */
    public function addField()
    {
        $model_id = input('model_id/d');
    	if ($model_id <= 0 || !is_numeric($model_id)) $this->error('参数错误');

        $model_type = get_model_type($model_id);
		
	    if ($this->request->isPost()) {
		    $data = $this->request->post();
			
			// 非独立模型需验证字段名称是否为aid
            if ($model_type != 2) {
                // 非独立模型需验证新增的字段是否被系统占用
                if ($data['en_title'] == 'aid' || is_default_field($data['en_title'])) {
                    $this->error('字段名称已存在');
                }
            }
				
			$result   = $this->validate($data, 'Field');
			if (true !== $result) $this->error($result);
			
			if ($field = FieldModel::create($data)) {
                $FieldModel = new FieldModel();
                // 添加字段
                if ($FieldModel->newField($data)) {
                    cache('lyear_system_fields', null);
                    $this->success('新增成功', url('fieldList', 'model_id='.$data['model_id']));
                } else {
                    // 添加失败，删除新增的数据
                    FieldModel::destroy($field['id']);
                    $this->error($FieldModel->getError());
                }
            } else {
                $this->error('新增失败');
            }
		} else {
			$types = config('app.site_setting.form_item_type');

            $modelTitle = DataModelModel::where('id', $model_id)->value('title');
			
			if ($model_type != 2) {
				$field_exist   = FieldModel::where('model_id', 'in', [0, $model_id])->column('en_title');
				$field_exist[] = 'aid';
			} else {
				$field_exist = ['id','cid','title','model_id','create_time','update_time','sort','status','clicks'];
			}
			
			$this->assign([
			    'model_id'    => $model_id,
			    'types'       => $types,
				'field_exist' => $field_exist,
                'title'       => $modelTitle . '模型 - 添加字段'
			]);
		    return $this->fetch();
		}
    }

    /**
     * 数据模型 - 编辑字段
     */
    public function editField()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');

	    if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result   = $this->validate($data, 'Field');
            if (true !== $result) $this->error($result);

            // 更新字段信息
            $FieldModel = new FieldModel();
            if ($FieldModel->updateField($data)) {
                if ($FieldModel->isUpdate(true)->save($data)) {
                    $this->success('字段更新成功', url('fieldList', 'model_id='.$data['model_id']));
                }
            }
            $this->error('字段更新失败');
		} else {
			$info = FieldModel::get($id);

            $modelTitle = DataModelModel::where('id', $info['model_id'])->value('title');
			
			$this->assign([
			    'info'  => $info,
                'title' => $modelTitle . '模型 - 编辑字段'
			]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 删除
	 * @param integer $ids id值
	 */
	public function deleteField($ids = null)
	{
		if ($ids === null) $this->error('参数错误');

        $FieldModel = new FieldModel();
        $field      = $FieldModel->where('id', $ids)->find();

        if ($FieldModel->deleteField($field)) {
            if ($FieldModel->where('id', $ids)->delete()) {
                $this->success('删除成功');
            }
        }
        return $this->error('删除失败');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setFieldStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = FieldModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }
}